﻿using ConfExpert.Forms;
using ConfExpert.Utility;
using DevExpress.XtraSplashScreen;

using DevTeamIT;
using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace ConfExpert
{
    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController(bool izinver)
        {
            IsSingleInstance = izinver;
            StartupNextInstance += this_StartupNextInstance;
        }

        public void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            if (e.CommandLine.Count > 0)
            {
                for (int i = 0; i < e.CommandLine.Count; i++)
                {
                    string fileName = e.CommandLine[i];

                    if ("ORHAN-PC ERP".Contains(Environment.MachineName))
                        MessageBox.Show(fileName);

                    fileName = fileName.Replace("file:///", "").Replace("/", @"\");
                    if (File.Exists(fileName))
                        CommandManager.ExecuteFile(fileName);
                }
            }
            e.BringToForeground = true;
        }

        protected override void OnCreateMainForm()
        {
            using (Login login = new Login())
                if (login.ShowDialog() == DialogResult.OK)
                {
                    Session.LaunchingTime = DateTime.Now;

                    SplashScreenManager.ShowForm(typeof(SplashLogin));
                    AppSession.MainForm = new MainForm();

                    AppSession.MainForm.WindowState = FormWindowState.Minimized;
                    AppSession.MainForm.ShowInTaskbar = false;

                    MainForm = AppSession.MainForm;
                }
                else
                {
                    Form dummy = new Form();
                    MainForm = dummy;
                    dummy.Close();
                }
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            //Microsoft.Win32.SystemEvents.UserPreferenceChanged += delegate { };

            InitLookAndFeel();

            Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);

            // Add the event handler for handling non-UI thread exceptions to the event. 
            AppDomain.CurrentDomain.UnhandledException += new System.UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                Session.Version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();

            bool biz = false; // (Environment.MachineName.ToUpper() == "");
            SingleInstanceController controller = new SingleInstanceController(biz);

            try
            {
                string[] args = new string[] { };
                controller.Run(args);
            }
            catch
            { }
        }

        private static void InitLookAndFeel()
        {
            Application.EnableVisualStyles();
            //Enable form skins here:
            DevExpress.Skins.SkinManager.EnableFormSkins(); // IfNotVista();
            DevExpress.Skins.SkinManager.EnableMdiFormSkins();

            //Register the skins with the application
            DevExpress.UserSkins.BonusSkins.Register();

            //Register the skins with the designer
            DevExpress.Skins.SkinManager.Default.RegisterAssembly(typeof(DevExpress.UserSkins.OfficeSkins).Assembly);
            //DevExpress.Skins.SkinManager.Default.RegisterAssembly(typeof(DevExpress.UserSkins.BonusSkins).Assembly);

            Application.SetCompatibleTextRenderingDefault(false);
            //DevExpress.LookAndFeel.LookAndFeelHelper.ForceDefaultLookAndFeelChanged();

            /*
             * There is one exception in Devexpress framework. The NavBarControl does not use the skin technology automatically from your global LookAndFeel object, you need to specify a setting to enable that:
            NavBarControl.PaintStyleName = "SkinNavigationPane";
            */
        }

        static void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            LogManager.LogToDB(ex);
        }
    }

    public class ThreadExceptionHandler
    {
        public void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            Type type = ex.GetType();

            if (type == typeof(ApplicationException))
                LogManager.Notify(ex);
            else //else if (! (e.Exception.ToString().Contains("0x80131904") && e.Exception.ToString().Contains("RepositoryManager.RefreshData")))
                LogManager.LogToDB(ex);
        }
    }
}